// pages/home/me.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

Page({
    // 为实现类似vue的computed、watch属性
    // 在app.js将computedBehavior挂载到wx上，实际起作用的是behavior属性，通过behaviors注入
    // behaviors: [wx.computedBehavior.behavior],

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        // 导航栏数据
        styledata: {
            "bg_color": "#fff",
            "color": "#000",
            "name": "我的"
        },
        islogin: false,
        isVip: false,
        endTime: '',
        uid: '',
        avatarUrl: defaultAvatarUrl,
        nickName: '游客',
        openId: '',
        session_key: '',
        myinfo: {
            point: 0,
            balance: 0,
            commission: '00.00',
            mobile: ''
        },
        // 用户积分
        point: 0,
        more_list: [],
        userInfo: {},
        service_list: [
            // {
            //     title: '领券中心',
            //     icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/个人中心图片/砍价记录.png',
            //     page_url: '/coupon/couCenter',
            // },
            {
                title: '地址信息',
                icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/location_gray.png',
                page_url: '/pages/address/address',
            },
            {
                title: '事业中心',
                icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/home-img/25.png',
                page_url: '/distribution/distributor/distributor',
            },
            {
                title: '认证中心',
                icon: 'http://img.jinding.gzzsu.com/shop/jin/IdCheck2.png',
                page_url: '/distribution/choice/choice',
            },
            {
                title: '代订服务',
                icon: 'http://img.jinding.gzzsu.com/shop/jin/dai2.png',
                page_url: '/distribution/assistacode/assistacode',
                // page_url: '/distribution/assistorder/assistorder',

            },
            {
                title: '采购服务',
                icon: 'http://img.jinding.gzzsu.com/shop/jin/purchase.png',
                page_url: '/wholesale/index',
                // page_url: '/distribution/assistorder/assistorder',

            },
            {
                title: '舌诊',
                icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/home-img/19.png',
                page_url: '/pages/tongue/tongue',
            },
            // {
            //   title: '联系客服',
            //   icon: '/images/个人中心图片/联系客服.png',
            //   num: 0,
            //   page_url: '/pages/blank/blank',
            // },
            // {
            //   title: '任务中心',
            //   icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/个人中心图片/砍价记录.png',
            //   num: 0,
            //   page_url: '/pages/region/index',
            // },

            // {
            //   title: '赠品',
            //   icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/个人中心图片/砍价记录.png',
            //   num: 0,
            //   page_url: '/pages/blank/blank',
            // },
        ],
        orderMenu: [{
            id: '0',
            title: '待付款',
            icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/waitpay4.png',
            num: 0,
            targetUrl: '/pages/order/list?index=1&status=1',
        },
        {
            id: '1',
            title: '待发货',
            icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/waitfa5.png',
            num: 0,
            targetUrl: '/pages/order/list?index=2&status=2'
        },
        {
            id: '2',
            title: '待收货',
            icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/waitshou2.png',
            num: 0,
            targetUrl: '/pages/order/list?index=3&status=3'
        },
        {
            id: '3',
            title: '待评价',
            icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/waitcomment.png',
            num: 0,
            targetUrl: '/pages/order/list?index=4&status=4'
        },
        {
            id: '4',
            title: '退款/售后',
            icon: 'http://img.qian.gzzsu.com/shop/qiankanghui/service.png',
            num: 0,
            targetUrl: '/pages/order/list?index=5&status=5'
        },
        ],
        options: {},

        // 领取优惠券数目
        couponNum: 0,

        // 积分增长数
        increaseNum: 0,
        // 是否展示积分增长数
        ifshowIncrease: true,


        /* 
        测试
        kkko: 55,
        kkkppp: 666,
        testWatch: {
            a: 5,
            b: 6
        } */
    },

    /* computed: {
        summm(data) {
            console.log('this', this);
            console.log(data.kkko);
            return data.kkko + data.kkkppp
        }
    },
    watch: {
        // 注意方法名必须是监视的属性，多属性用逗号分隔，可用通配符深度监视
        // 参数为监视的属性最新值
        'testWatch.**': function (testWatch) {
            console.log(testWatch);
            console.log('watch', this.data.summm);
        }
    }, */

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        // onLoad中可以访问到计算属性
        // console.log(this.data.summm);
        // 测试watch
        // setTimeout(() => {
        //     this.setData({
        //         'testWatch.a': 500
        //     })
        // }, 3000);

        this.init_data(options)
        if (this.data.uid) {
            this.get_myinfo()
            // this.queryWmemberInfo()
        }


        // this.get_open_id()
        // this.get_more_list()
        // this.getOrderNum()
        // this.getMyCoupons()

        // 获取上次退出小程序 积分数
        this.lastLoginpoint = wx.getStorageSync('lastLoginPoint') ? wx.getStorageSync('lastLoginPoint') : 0
    },

    init_data(options) {
        let endTime = ''
        if (App.globalData.VipGrade > 0) {
            endTime = App.globalData.fulluserInfo.end_time
            let arr = endTime.split(' ')
            endTime = arr[0].replace(/-/g, '/')
        }
        this.setData({
            uid: App.globalData.uid,
            userInfo: App.globalData.userInfo,
            islogin: App.globalData.islogin,
            isVip: App.globalData.isVip,
            endtime: App.globalData?.fulluserInfo?.end_time,
            avatarUrl: App.globalData?.fulluserInfo?.avatar || defaultAvatarUrl,
            nickName: App.globalData?.fulluserInfo?.name || '游客',
            endTime,
            options,
        })

    },

    setDefaultAvatar() {
        this.setData({
            avatarUrl: defaultAvatarUrl
        })
    },

    getOrderNum() {
        const that = this
        let orderMenu = this.data.orderMenu
        orderMenu.forEach((item, index) => {
            let params = {
                uid: this.data.uid,
                status: index + 1,
                page: 1,
                limit: 50
            }
            wx.request({
                url: api.orderlist,
                data: params,
                method: 'POST',
                header: {
                    'Content-Type': 'application/json',
                    'Authorization': wx.getStorageSync('easy_schedule_token')
                },
                success(res) {
                    if (res.statusCode == 200) {
                        if (res.data.code == 0) {
                            let temstr = `orderMenu[${index}].num`

                            // 售后的订单只显示'售后中'的单
                            if (index == 4) {
                                let services = res.data.data
                                let servicingNum = 0
                                services.forEach(item => {
                                    if (item.status == 8) servicingNum++
                                });
                                that.setData({
                                    [temstr]: servicingNum
                                })
                                return
                            }

                            that.setData({
                                [temstr]: res.data.count
                            })
                        } else {
                            let reg = /uid不能为空/
                            if (reg.test(res.data.msg)) {
                                res.data.msg = '您未登录'
                            }
                            wx.showToast({
                                title: res.data.msg,
                                icon: 'none'
                            });
                        }

                    } else if (res.statusCode == 401) {
                        reject("登录已过期")
                        wx.showModal({
                            title: '提示',
                            content: '登录已过期，请立即登录，否则无法正常使用',
                            success(res) {
                                if (res.confirm) {
                                    console.log('用户点击确定')
                                    wx.switchTab({
                                        url: '/pages/home/me',
                                    })
                                } else if (res.cancel) {
                                    console.log('用户点击取消')
                                }
                            }
                        })
                    }
                },
                fail: function (err) {
                    console.log(err)
                }
            })
        });
    },

    // 获取本用户所有已领取的优惠券数量
    async getMyCoupons() {
        // type: 0 所有记录、1 未使用、2 已使用、3 已失效
        let params = {
            uid: App.globalData.uid,
            type: 1
        }
        let myCoulist = await request.post(api.myCouponList, params)

        this.setData({
            couponNum: myCoulist ? myCoulist.length : 0
            // couponNum: myCoulist.length

        })
    },

    // 券类型变更事件
    onChangeType(e) {
        // console.log('类型', e);
        this.setData({
            'couType.value': e.detail.value,
        });
        // console.log(this.data.couType.value);

    },

    // 通过api获得登录临时凭证，携带到后台获取openId和登录session
    // async get_open_id() {
    //     let flag = await App.gologin()
    //     if (flag) {
    //         this.init_data(this.data.options)
    //     }
    // },

    // 没有获得openId情况下也能调用获取基本的灰色头像和昵称
    // wx.getUserProfile 所拿到的userInfo是微信昵称和灰色头像
    get_user_profile() {
        wx.getUserProfile({
            desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: res => {
                console.log('profile', res);
                App.globalData.userInfo = res.userInfo
                util.saveAppValue('userInfo', res.userInfo)
                this.setData({
                    avatarUrl: res.userInfo.avatarUrl,
                    nickName: res.userInfo.nickName
                })
            },
            fail: res => {
                console.log(res);
            }
        })
    },

    // 登录包括两个流程 获取openId 获取默认的头像昵称
    async go_login() {
        // await App.confirmLogin()
        // console.log(App.globalData.uid);

        // this.get_open_id()
        let flag = await App.gologin()
        if (flag) {
            this.init_data(this.data.options)
            this.get_myinfo()
            this.getOrderNum()
            this.getMyCoupons()
        }
    },

    // 商品列表组件点击加入购物车
    async cart_add(e) {
        if (!this.data.uid) {
            util.showToast('请登录后再添加购物车哦')
            return
        }
        let id = e.detail.currentTarget.dataset.id

        let goodDetail = await request.post(api.goods_details, { id })
        if (goodDetail.store_nums <= 0) {
            wx.showToast({
                title: '该商品暂无库存，请挑选别的心仪商品吧',
                icon: 'none',
                duration: 2000
            });
            return
        }

        let params = {
            goods_id: id,
            uid: this.data.uid
        }
        let res = await request.post(api.cart_add, params)
        if (res) {
            let cartRes = await request.post(api.cart_list, { uid: this.data.uid })
            // console.log(cartRes);
            App.globalData.cartnum = cartRes.total_goods_nums
        }
        util.showToast("已加入购物车")
    },

    get_more_list() {
        let params = {
            // key: this.data.keyword_value,
            // uid: this.data.uid,
            brand_id: 2
        }
        util.showLoading('加载中')
        request.post(api.goods_more, params).then(res => {
            util.hideLoading()
            for (var i = 0; i < res.length; i++) {
                let mx = parseInt(Math.random() * 10) / 10
                let youhui = res[i].sell_price * (mx * 0.04 + 0.08)
                res[i].youhui = youhui.toFixed(2)
                //  console.log(mx + ' random ')
                //  console.log(res[i].youhui + ' youhui ')
            }
            this.setData({
                more_list: res
            })
        })
    },

    go_detail_from_component(e) {
        let id = e.detail.currentTarget.dataset.id
        if (!id) {
            id = 10
        }
        wx.navigateTo({
            url: '/pages/good/detail?id=' + id,
        })
    },

    go_vip() {
        let url = '/vip/vip'
        wx.navigateTo({
            url,
        })
    },

    get_myinfo() {
        let params = {
            uid: this.data.uid
        }
        request.post(api.myinfo, params).then(res => {
            this.setData({
                myinfo: res
            })
        })
    },

    changeAvatar() {
        let url = '/pages/myinfo/avatar'
        wx.navigateTo({
            url,
        })
    },

    // 用户点击登录回调
    go_service(e) {
        var targetUrl = e.currentTarget.dataset.url;
        let distributionApply = `/distribution/distributor/distributor`
        let distributionCenter = `/distribution/index/index`

        let mobile = this.wDetail?.allin_moblie ? this.wDetail.allin_moblie : ""
        let truename = this.wDetail?.true_name ? this.wDetail.true_name : ""
        let isVip = this.data.isVip
        console.log('mobile.length', mobile, mobile.length);

        if (targetUrl == distributionApply) {
            let isDistributor = false

            // 分销员身份(已在通联注册会员、实名认证、绑定手机、充值金顶会员) 直接跳转事业中心首页
            if (mobile.length == 11 && truename !== "" && isVip) {
                isDistributor = true
            }
            if (isDistributor) targetUrl = distributionCenter
        }

        wx.navigateTo({
            url: targetUrl,
            success: function (res) {
                console.log(res);
            },
            faul: function (err) {
                console.log(err);
            }
        });
    },
    go_order() {
        wx.navigateTo({
            url: '/pages/order/list?index=0&status=0',
        })
    },
    go_order_another(e) {
        // console.log(e);
        let url = e.currentTarget.dataset.url
        wx.navigateTo({
            url,
        })
    }
    ,

    showexpectTip() {
        util.showToast('敬请期待~')
    },

    // 查询会员提现余额
    async queryBalance() {
        let Balance = await request.postall(api.checkAllinBalance, { uid: this.data.uid })
        if (Balance.code == 0) {
            let allAmount = (Balance.data.allAmount / 100).toFixed(2)
            // console.log("余额", Balance, allAmount);
            this.setData({
                availableMoney: allAmount
            })
        } else {
            this.setData({
                availableMoney: "0.00"
            })
        }
    },

    // 查询提现人员详细信息
    async queryWmemberInfo() {
        let wDetail = await request.post(api.queryWmemberInfo, { uid: this.data.uid })
        console.log("提现人详情", wDetail);

        // 提现人员详情不显示在页面 无需记录在data中
        this.wDetail = wDetail
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 自定义底部栏保证选择无误的代码
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                cartnum: App.globalData.cartnum,
                selected: 4
            })
        }

        // 检测是否有头像昵称修改
        let isVip = App.globalData.isVip
        let avatarUrl = App.globalData?.fulluserInfo?.avatar
        let nickName = App.globalData?.fulluserInfo?.name
        let mobile = App.globalData?.fulluserInfo?.mobile
        let endtime = App.globalData?.fulluserInfo?.end_time

        // console.log('66666', this.data.endtime, endtime);
        if (this.data.endtime != endtime || this.data.isVip != isVip || this.data.avatarUrl != avatarUrl || this.data.nickName != nickName || this.data.myinfo.mobile != mobile) {
            this.init_data(this.data.options)
        }

        // 更新积分
        this.updatePoint()

        // 检测是否有个人信息
        if (!this.data.myinfo?.name && this.data.uid) {
            this.get_myinfo()
        }

        if (this.data.uid) {
            this.getOrderNum()
            this.getMyCoupons()
        }

        // 查询可提现余额
        this.queryBalance()
        this.queryWmemberInfo()
    },

    useLast: true, // 是否上次退出登录积分数
    lastLoginpoint: 0,

    // 更新积分、判断是否展示
    async updatePoint() {
        let params = {
            uid: this.data.uid
        }
        let res = await request.post(api.myinfo, params)
        let lastpoint = 0
        if (this.useLast) {
            lastpoint = this.lastLoginpoint // 页面第一次加载，使用上次积分数
            this.useLast = false
        } else {
            lastpoint = this.data.point // 第一次后使用，当前页面的积分数
        }

        let newpoint = res.point
        let increaseNum = newpoint - lastpoint
        this.setData({
            point: newpoint,
            increaseNum,
            ifshowIncrease: increaseNum > 0 ? true : false
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        wx.setStorageSync('lastLoginPoint', this.data.point)

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // wx.setStorageSync('lastLoginPoint', this.data.point)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})